package com.example.demo1.controller;

import com.example.demo1.pojo.dto.productCreateDto;
import com.example.demo1.pojo.product;
import com.example.demo1.pojo.result.result;
import com.example.demo1.service.productService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/products")
@Validated
@CrossOrigin(origins = "*")
public class productController {
    @Autowired
    private productService productService;

    @PostMapping
    public result<product> createProduct(@Valid @RequestBody productCreateDto productDto) {
        try{
            product product = productService.createProduct(productDto);
            return result.success("product create success",product);
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }

    @GetMapping
    public result<List<product>> getAllProducts() {
        try {
            List<product> products = productService.getAllProducts();
            return result.success(products);
        } catch (Exception e) {
            return result.error(e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public result<product> getProduct(@PathVariable Integer id) {
        try{
            Optional<product> productOpt=productService.getProductById(id);
            if(productOpt.isPresent()){
                return result.success(productOpt.get());
            }else{
                return result.error("product not exist");
            }
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public result<product> updateProduct(@PathVariable Integer id
            ,@Valid @RequestBody productCreateDto productDto) {
        try{
            product product=productService.updaetProduct(id,productDto);
            return result.success("product update success",product);
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public result<product> deleteProduct(@PathVariable Integer id) {
        try{
            productService.deleteProduct(id);
            return  result.success("product delete success",null);
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }

    @GetMapping("/available")
    public result<List<product>> getAvailableProducts() {
        try{
            List<product> products=productService.getAvailableProducts();
            return result.success(products);
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }
}
